//
//  ChangePhoneViewController.m
//  ShowYork
//
//  Created by hxh on 2020/10/13.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "ChangeNewPhoneViewController.h"
#import "MineAccountSetViewController.h"
#import "LoginAndRegisterTitleView.h"

#import "HWTFCursorView.h"

@interface ChangeNewPhoneViewController ()
/// 标题
@property (nonatomic,strong)LoginAndRegisterTitleView *titleView;
/// 输入框
@property (nonatomic,strong)UITextField *phoneTF;
/// 验证码code
@property (nonatomic,strong)UITextField *codeTF;
/// 发送按钮
@property (nonatomic,strong)UIButton *sendBtn;

@property (nonatomic,strong)UIView *phoneLine;

@property (nonatomic,strong)UIView *codeLine;

@property (nonatomic,strong)UIButton *confirmBtn;

@property (nonatomic,copy)NSString *oldPhone;

@property (nonatomic,copy)NSString *oldCode;

@end

@implementation ChangeNewPhoneViewController


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = YES;
    
    [IQKeyboardManager sharedManager].enable = NO;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    
    blackLineImageView.hidden = NO;
    
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor = [UIColor colorWithHexString:@"#666666"];
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
    
    [IQKeyboardManager sharedManager].enable = YES;
   
}


- (instancetype)initWithOldPhone:(NSString *)oldPhone oldCode:(NSString *)oldCode{
    if (self = [super init]) {
        self.oldCode = oldCode;
        self.oldPhone = oldPhone;
    }
    return self;
}


#pragma mark - 懒加载
- (LoginAndRegisterTitleView *)titleView{
    if (!_titleView) {
        _titleView = [[LoginAndRegisterTitleView alloc]initWithMainTitle:@"验证新手机号" andSubTitle:@"为了您的帐户安全，请验证手机号"];
    }
    return _titleView;
}
- (UITextField *)phoneTF{
    if (!_phoneTF) {
        _phoneTF = [[UITextField alloc]init];
        _phoneTF.placeholder = @"请输入手机号";
        _phoneTF.tintColor = RGBA(245, 75, 100, 1);
        _phoneTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        _phoneTF.keyboardType = UIKeyboardTypeNumberPad;
        _phoneTF.textColor = C51;
        _phoneTF.font = font(14);
        [_phoneTF addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
        _phoneTF.returnKeyType = UIReturnKeyDone;
        [_phoneTF becomeFirstResponder];
    }
    return _phoneTF;
}

- (UITextField *)codeTF{
    if (!_codeTF) {
        _codeTF = [[UITextField alloc]init];
        _codeTF.tintColor = RGBA(245, 75, 100, 1);
        _codeTF.placeholder = @"请输入短信验证码";
        _codeTF.keyboardType = UIKeyboardTypeNumberPad;
        _codeTF.returnKeyType = UIReturnKeyDone;
        _codeTF.font = font(14);
        _codeTF.textColor = C51;
        [_codeTF addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
        if (@available(iOS 12.0, *)) {
            _codeTF.textContentType = UITextContentTypeOneTimeCode;
        } else {
            // Fallback on earlier versions
        }
    }
    return _codeTF;
}

- (UIView *)phoneLine{
    if (!_phoneLine) {
        _phoneLine = [[UIView alloc]init];
        _phoneLine.backgroundColor = RGBA(230, 230, 230, 1);
    }
    return _phoneLine;
}
- (UIView *)codeLine{
    if (!_codeLine) {
        _codeLine = [[UIView alloc]init];
        _codeLine.backgroundColor = RGBA(230, 230, 230, 1);
    }
    return _codeLine;
}
- (UIButton *)confirmBtn{
    if (!_confirmBtn) {
        _confirmBtn = [[UIButton alloc]init];
        _confirmBtn.layer.cornerRadius = 22;
        _confirmBtn.layer.masksToBounds = YES;
        [_confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_confirmBtn setTitleColor:RGBA(255, 255, 255, 1) forState:UIControlStateDisabled];
        [_confirmBtn setBackgroundImage:[UIImage imageNamed:@"login_confirm_normal_tag"] forState:UIControlStateDisabled];
        [_confirmBtn setBackgroundImage:[UIImage imageNamed:@"login_confirm_selected_tag"] forState:UIControlStateNormal];
//        [_codeBtn setBackgroundImage:[UIImage imageNamed:@"login_bg_tag"] forState:UIControlStateNormal];
        [_confirmBtn addTarget:self action:@selector(confirmMethod) forControlEvents:UIControlEventTouchUpInside];
        _confirmBtn.enabled = NO;
    }
    return _confirmBtn;
}

- (UIButton *)sendBtn{
    if (!_sendBtn) {
        _sendBtn = [[UIButton alloc]init];
        [_sendBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_sendBtn setTitleColor:[RPAppManager themColor] forState:UIControlStateNormal];
        [_sendBtn setTitleColor:RGBA(204,204, 204, 1) forState:UIControlStateDisabled];
        [_sendBtn addTarget:self action:@selector(sendMethod) forControlEvents:UIControlEventTouchUpInside];
        _sendBtn.titleLabel.font = font(10);
        _sendBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        _sendBtn.enabled = NO;
        
    }
    return _sendBtn;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.titleView];
    [self.view addSubview:self.phoneTF];
    [self.view addSubview:self.codeTF];
    [self.view addSubview:self.codeLine];
    [self.view addSubview:self.phoneLine];
    [self.view addSubview:self.confirmBtn];
    [self.view addSubview:self.sendBtn];
        
    [self.titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(16 + GK_STATUSBAR_HEIGHT);
        make.right.equalTo(self.view.mas_right);
        make.left.equalTo(self.view.mas_left).offset(25);
    }];
    
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight).offset(-25);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft).offset(25);
        }else{
            make.right.equalTo(self.view.mas_right).offset(-25);
            make.left.equalTo(self.view.mas_left).offset(25);
        }
        make.top.equalTo(self.titleView.mas_bottom).offset(40);
        make.height.mas_equalTo(44);
    }];
    [self.codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneTF.mas_bottom).offset(16);
        make.height.mas_equalTo(44);
        if (@available(iOS 11,*)) {
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight).offset(-25);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft).offset(25);
        }else{
            make.right.equalTo(self.view.mas_right).offset(-25);
            make.left.equalTo(self.view.mas_left).offset(25);
        }
    }];
    
    [self.phoneLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.phoneTF);
        make.height.mas_equalTo(0.5);
    }];
    [self.codeLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.codeTF);
        make.height.mas_equalTo(0.5);
    }];
    
    [self.confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.codeLine.mas_bottom).offset(50);
        make.height.mas_equalTo(44);
        if (@available(iOS 11,*)) {
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight).offset(-24);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft).offset(24);
        }else{
            make.left.equalTo(self.view).offset(24);
            make.right.equalTo(self.view).offset(-24);
        }
    }];
    
    [self.sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.equalTo(self.codeTF);
        make.width.mas_equalTo(80);
    }];
    
    
    Ivar ivar =  class_getInstanceVariable([UITextField class], "_placeholderLabel");
    UILabel *placeholderLabel1 = object_getIvar(self.codeTF, ivar);
    placeholderLabel1.textColor = RGBA(204, 204, 204, 1);
    
    UILabel *placeholderLabel2 = object_getIvar(self.phoneTF, ivar);
    placeholderLabel2.textColor = RGBA(204, 204, 204, 1);
    
    self.titleView.mainColor = RGBA(35, 24, 21, 1);
    self.titleView.subColor = C153;
}

- (void)confirmMethod{
    [SVProgressHUD show];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone"] = self.phoneTF.text;
    param[@"code"] = self.codeTF.text;
    param[@"md5"] = [RPAppManager md5StrWithApi:ChangePhoneAndValidCode];
    param[@"id"] = [RPAppManager getCustomerId];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(ChangePhoneAndValidCode) parames:param success:^(id responseObj) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"更换成功" duration:2 finishHandler:nil];
        
        UserInfoModel *userInfo = [UserInfoModel userInfo];
        userInfo.phone = self.phoneTF.text;
        [userInfo save];
        
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:self.oldPhone];
        [[NSUserDefaults standardUserDefaults]setObject:self.phoneTF.text forKey:self.phoneTF.text];
        [[NSUserDefaults standardUserDefaults]synchronize];
        __block NSInteger index = -1;
        [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[MineAccountSetViewController class]]) {
                index = idx;
                *stop = YES;
            }
        }];
        if (index != -1) {
            [self.navigationController popToViewController:self.navigationController.viewControllers[index] animated:YES];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updatePhone" object:nil];
        
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}
- (void)sendMethod{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"oldPhone"] = self.oldPhone;
    param[@"oldPhoneCode"] = self.oldCode;
    param[@"newPhone"] = self.phoneTF.text;
    param[@"id"] = [RPAppManager getCustomerId];
    param[@"md5"] = [RPAppManager md5StrWithApi:ChangePhoneAndSendCodeToNewPhone];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(ChangePhoneAndSendCodeToNewPhone) parames:param success:^(id responseObj) {
       
        __block NSInteger time = 59;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(timer,DISPATCH_TIME_NOW,1.0*NSEC_PER_SEC, 0);
        dispatch_source_set_event_handler(timer, ^{
            if (time <= 0) {
                dispatch_source_cancel(timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.sendBtn.enabled = YES;
                    [self.sendBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                });
            }else{
                int seconds = time % 60;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.sendBtn setTitle:[NSString stringWithFormat:@"%.2d秒",seconds] forState:UIControlStateDisabled];
                    self.sendBtn.enabled = NO;
                });
                time--;
            }
        });
        dispatch_resume(timer);
        
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}


- (void)textDidChange:(UITextField *)textField{
    
    if (textField == self.phoneTF) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringWithRange:NSMakeRange(0, 11)];
        }
        
        if (textField.text.length == 11 && [[textField.text substringToIndex:1] isEqualToString:@"1"]) {
            self.sendBtn.enabled = YES;
        }else{
            self.sendBtn.enabled = NO;
        }
    }
    
    if (self.codeTF.text.length > 0 && self.phoneTF.text.length == 11) {
        self.confirmBtn.enabled = YES;
    }else{
        self.confirmBtn.enabled = NO;
    }
}



- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}


@end
